/**
 * 全站http配置
 *
 */
import axios from 'axios';
import router from '@/router/index';
import {Message} from 'iview';

//默认超时时间
axios.defaults.timeout = 20000;

axios.defaults.baseURL = window.gconfig.baseURL;

//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

//http request拦截
axios.interceptors.request.use(config => {
    //让每个请求携带token
    var satoken = window.$localStorage.getItem('saToken');
    if (satoken) {
        config.headers["satoken"] = satoken;
    }
    return config
}, error => {
    return Promise.reject(error)
});
//http response 拦截
axios.interceptors.response.use(res => {

    //获取状态码
    const status = res.data.code || res.status;

    const message = res.data.msg || res.data.error_description || '未知错误';
    //如果是401则跳转到登录页面
    if (status === 401) {
        Message.error(message);
        router.push({name: 'home'})
    }
    return res;
}, error => {
    Message.error(error);
});

export default axios;
